import React, { Component } from 'react';
import {
  Form,
  Input,
  Table,
  Button,
  Select,
  Tag,
  Modal,
  Radio,
  Row,
  Divider,
  Col,
  Alert,
  DatePicker,
  Popconfirm,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import moment from 'moment';
import Add from './add';
import Edit from './edit';
import { connect } from 'dva';
const { MonthPicker, RangePicker } = DatePicker;
const { Option } = Select;

@connect(({ cost, order }: any) => ({
  datasource: cost.list,
  total: cost.total,
  isRefresh: cost.isRefresh,
  personData: order.personData,
}))
class Index extends Component<any, any> {
  state = {
    selectDate: 'day',
    visible: false,
    edit: false,
    size: 10,
    currentPage: 1,
    comments: '',
    startTime: 0,
    endTime: Date.now(),
  };
  componentDidMount() {
    // this.handleSearch();
    this.props.dispatch({
      type: 'cost/reFresh',
      payload: true,
    });
  }
  componentDidUpdate() {
    const { isRefresh } = this.props;
    if (isRefresh) {
      this.handleSearch();
    }
  }
  handleSearch = () => {
    const { dispatch } = this.props;
    const { size, currentPage, startTime, endTime } = this.state;
    dispatch({
      type: 'cost/list',
      payload: {
        size: size,
        page: currentPage,
        startTime,
        endTime,
      },
    });
  };
  handlSelect = e => {
    this.setState({ selectDate: e.target.value });
  };
  handleOpenModal = e => {
    this.setState({
      visible: true,
    });
  };
  handleOk = e => {
    this.formRef.handleSubmit();
  };
  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };
  render() {
    const { selectDate, visible, edit, size, currentPage } = this.state;
    const { datasource, total, isRefresh, personData } = this.props;
    const columns = [
      {
        title: '序号',
        align: 'center',
        render: (text, record, index) => `${index + 1}`,
      },
      {
        title: '人员姓名',
        dataIndex: 'staffName',
        align: 'center',
      },
      {
        title: '支出费用',
        dataIndex: 'cost',
        align: 'center',
      },
      // {
      //   title: '类型',
      //   dataIndex: 'cost',
      //   align: 'center',
      // },
      // {
      //   title: '订单运费',
      //   dataIndex: 'comments',
      //   align: 'center',
      // },
      // {
      //   title: '订单其它费用',
      //   dataIndex: 'comments',
      //   align: 'center',
      // },
      {
        title: '费用类型',
        dataIndex: 'unitName',
        align: 'center',
      },
      {
        title: '备注',
        dataIndex: 'comments',
        align: 'center',
      },
      {
        title: '支出时间',
        dataIndex: 'costTime',
        align: 'center',
        render: (text: any) => {
          return (
            <>
              <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
            </>
          );
        },
      },

      {
        title: '操作',
        dataIndex: 'operate',
        align: 'center',
        render: (text: any, record: any, index: any) => {
          const id = record.id;
          return (
            <span>
              <a
                onClick={() => {
                  this.setState(
                    {
                      edit: true,
                    },
                    () => {
                      this.props.dispatch({
                        type: 'cost/view',
                        payload: record,
                      });
                    },
                  );
                }}
              >
                修改
              </a>
              <Divider type="vertical" />
              <Popconfirm
                title="你确定要删除该条信息嘛？"
                onConfirm={() => {
                  this.props.dispatch({
                    type: 'cost/delete',
                    payload: { ids: id },
                  });
                }}
                onCancel={() => {}}
                okText="Yes"
                cancelText="No"
              >
                <a href="#">删除</a>
              </Popconfirm>
            </span>
          );
        },
      },
    ];

    return (
      <PageHeaderWrapper>
        <div style={{ paddingLeft: '22px', marginBottom: '6px' }}>
          <Form layout="inline">
            <Form.Item label="工作人员">
              <Select
                showSearch
                placeholder="请输入工作人员"
                filterOption={false}
                onChange={() => {}}
                style={{ width: '180px' }}
              >
                {personData.length > 0
                  ? personData.map((item: any) => (
                      <Option value={item.id}>
                        {item.name} （{item.phoneNumber}）
                      </Option>
                    ))
                  : null}
              </Select>
            </Form.Item>
            <Form.Item label="时间：">
              {/* <Radio.Group
                value={selectDate}
                onChange={this.handlSelect}
                style={{ marginRight: '14px' }}
              >
                <Radio.Button value="day">日</Radio.Button>
                <Radio.Button value="month">月</Radio.Button>
                <Radio.Button value="period">时间段</Radio.Button>
              </Radio.Group> */}
              {/* {selectDate == 'day' ? (
                <DatePicker
                  size="default"
                  onChange={(val: any) => {
                    console.log(Number(moment(val).startOf('day')), 99999);
                    this.setState({
                      startTime: Number(moment(val).startOf('day')),
                      endTime: Number(moment(val).endOf('day')),
                    });
                  }}
                />
              ) : null}
              {selectDate == 'month' ? (
                <MonthPicker
                  placeholder="请选择月份"
                  format={'YYYY/MM'}
                  onChange={(date: any, dateString) => {
                    this.setState({
                      startTime: Number(moment(date).startOf('month')),
                      endTime: Number(moment(date).endOf('month')),
                    });
                  }}
                />
              ) : null} */}
              {/* {selectDate == 'period' ? ( */}
              <RangePicker
                // defaultValue={[moment(0), moment()]}
                ranges={{
                  今日: [moment(), moment()],
                  当月: [moment().startOf('month'), moment().endOf('month')],
                }}
                format="YYYY/MM/DD"
                onChange={([start, end]) => {
                  if (!start && !end) {
                    this.setState({
                      startTime: 0,
                      endTime: Date.now(),
                    });
                  } else {
                    this.setState({
                      startTime: Number(start),
                      endTime: Number(end),
                    });
                  }
                }}
              />
              {/* ) : null} */}
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                onClick={() => {
                  this.props.dispatch({
                    type: 'cost/reFresh',
                    payload: true,
                  });
                }}
                style={{ marginRight: '14px' }}
              >
                搜索
              </Button>
              <Button type="primary" onClick={this.handleOpenModal}>
                新增
              </Button>
            </Form.Item>
          </Form>
        </div>

        <div style={{ background: '#fff' }}>
          <Table
            bordered
            columns={columns}
            dataSource={datasource}
            loading={isRefresh}
            size="middle"
            pagination={{
              pageSizeOptions: ['10', '20', '30', '40'],
              showSizeChanger: true,
              total: total,
              pageSize: size,
              current: currentPage,
              onChange: (page: any, pageSize: any) => {
                this.setState(
                  {
                    currentPage: page,
                  },
                  () => {
                    this.handleSearch();
                  },
                );
              },
              onShowSizeChange: (current: any, size: any) => {
                this.setState(
                  {
                    size: size,
                  },
                  () => {
                    this.handleSearch();
                  },
                );
              },
            }}
          />
        </div>

        <Modal
          title="新增"
          visible={visible}
          destroyOnClose
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Add
            close={this.handleCancel}
            submit={(view: any, data: any) => {
              this.props.dispatch({
                type: 'cost/add',
                payload: { ...data, costTime: new Date(data.costTime).getTime() },
              });
            }}
            wrappedComponentRef={(form: any) => (this.formRef = form)} //5、使用wrappedComponentRef 拿到子组件传递过来的ref（官方写法）
          />
        </Modal>
        <Modal
          title="修改"
          visible={edit}
          destroyOnClose
          onOk={() => {
            this.editRef.handleSubmit();
          }}
          onCancel={() => {
            this.setState({
              edit: false,
            });
          }}
        >
          <Edit
            close={() => {
              this.setState({
                edit: false,
              });
            }}
            submit={(view: any, data: any) => {
              this.props.dispatch({
                type: 'cost/edit',
                payload: { ...view, ...data, costTime: new Date(data.costTime).getTime() },
              });
            }}
            wrappedComponentRef={form => (this.editRef = form)} //5、使用wrappedComponentRef 拿到子组件传递过来的ref（官方写法）
          />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default Index;
